package com.jl;

import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import lombok.Builder;
import lombok.Data;
import lombok.SneakyThrows;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * mybatisplus代码生成
 */
public class JLMybatisGenerator {

    @Data
    @Builder
    public static class Generator {
        //表名前缀
        private String tablePrefix;

        //作者
        private String author;

        //mysqlIp
        private String ip;

        //mysql库
        private String database;

        //mysql账号
        private String username;

        //mysql密码
        private String password;

        //实体父类
        private Class<?> baseEntity;

        //写于实体父类的表列 "id", "in_time", "modify_time"
        private String[] baseEntityPropertys;

        //控制器父类class
        private Class<?> baseController;

        //调用类的class
        private Class<?> clasz;

        public String getBaseEntity() {
            return baseEntity == null ? null : baseEntity.getName();
        }

        public String getBaseController() {
            return baseController == null ? null : baseController.getName();
        }


        @SneakyThrows
        public void create() {
            if (clasz == null) {
                String classname = new Exception().getStackTrace()[1].getClassName();
                clasz = Class.forName(classname);
            }
            generate(this);
        }
    }

    /**
     * 读取控制台内容
     */
    private static String[] scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        String str = scanner.next();
        String[] tables = str.split(",");
        return tables;
    }

    private static void generate(Generator generator) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();

        // 全局配置
        GlobalConfig gc = new GlobalConfig();

        Class<?> clasz = generator.getClasz();
        String packageStr = clasz.getPackage().getName();
        String path = clasz.getResource("/").getPath();
        path = path.replaceAll("target/classes/", "");

        gc.setOutputDir(path + "src/main/java");
        gc.setAuthor(generator.getAuthor());//作者名称
        gc.setOpen(false);
        gc.setFileOverride(true);
        gc.setActiveRecord(false);// 不需要ActiveRecord特性的请改为ftalse
        gc.setEnableCache(false);// XML 二级缓存
        gc.setBaseResultMap(true);// XML ResultMap
        gc.setBaseColumnList(false);// XML columList

        // 自定义文件命名，注意 %s 会自动填充表实体属性！
        gc.setControllerName("%sController");
        gc.setServiceName("%sService");
        gc.setServiceImplName("%sServiceImpl");
        gc.setMapperName("%sMapper");
        gc.setXmlName("%sMapper");
        mpg.setGlobalConfig(gc);

        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://" + generator.getIp() + "/" + generator.getDatabase() + "?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC&rewriteBatchedStatements=true&allowPublicKeyRetrieval=true");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername(generator.getUsername());
        dsc.setPassword(generator.getPassword());
        mpg.setDataSource(dsc);

        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setParent(packageStr);//父包名
        pc.setMapper("mapper");//mapper
        pc.setService("service");//servcie
        pc.setController("controller");//controller
        pc.setEntity("entity");//entity

        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };

        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";

        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        String finalPath = path;
        String finalPackageStr = packageStr;
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 ， 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化！！
                return finalPath + "src/main/java/" + finalPackageStr.replaceAll("\\.", "/") + "/mapper/mapper/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        mpg.setPackageInfo(pc);
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);

        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();

        // 配置自定义输出模板
        //此处设置为null，就不会再java下创建xml的文件夹了
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);

        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        if (!StringUtils.isEmpty(generator.getBaseEntity())) {
            // 实体公共父类
            strategy.setSuperEntityClass(generator.getBaseEntity());
            // 写于父类的表列
            strategy.setSuperEntityColumns(generator.getBaseEntityPropertys());
        }
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        if (!StringUtils.isEmpty(generator.getBaseController())) {
            // controller公共父类
            strategy.setSuperControllerClass(generator.getBaseController());
        }
        // 表名
        strategy.setInclude(scanner("表名，多个,号分开"));
        strategy.setControllerMappingHyphenStyle(true);
        //根据你的表名来建对应的类名，如果你的表名没有什么下划线，那么你就可以取消这一步
        if (!StringUtils.isEmpty(generator.getTablePrefix())) {
            strategy.setTablePrefix(generator.getTablePrefix());
        }
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }
}
